﻿using System;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools.Database
{
    public class Transaction
    {
        /// <summary>
        /// Creates inline transaction block
        /// </summary>
        /// <typeparam name="TSql">Sql provider type</typeparam>
        /// <param name="executeF">code to be executed inside transaction block</param>
        /// <param name="connection">connection string (optional)</param>
        public static void Block<TSql>(Action<TSql> executeF, string connection = null) where TSql : Sql
        {
            using (var sql = (TSql)Activator.CreateInstance(typeof(TSql), connection, null))
            {
                sql.BeginTransaction();
#if !DEBUG
                try
#endif
                {
                    executeF(sql);
                    sql.Commit();
                }
#if !DEBUG
                catch (Exception ex)
                {
                    sql.Rollback();
                    Log.Entry(LogSeverity.Error, ex.Message);
                    throw ex;
                }
#endif
            }
        }
    }
}
